﻿using Dynamicweb.Frontend;
using Dynamicweb.Extensibility;
using System.Web;
using System.Data;
using Dynamicweb;

namespace DwProjectTemplate.CustomModules.Subscribers
{
	[Subscribe( Dynamicweb.Notifications.Standard.Page.Loaded )]
	public class PrepInstaller : NotificationSubscriber
	{
		public override void OnNotify( string notification, object[] args )
		{
			if ( DwProjectTemplate.App.CodeSettings.EnablePrepInstaller )
			{
				if ( HttpContext.Current.Request[ "prepinstall" ] != null )
				{
					// Enable Dynamicweb Developer module
					using ( IDbConnection con = Database.GetConn( "Dynamic.mdb" ) )
					{
						IDbCommand cmd = con.CreateCommand();
						cmd.CommandText = "UPDATE [Module] SET [ModuleAccess]=" + Database.SqlBool( true ) + " WHERE [ModuleSystemName]='RegisterModule';";
						cmd.ExecuteNonQuery();
					}

					// Install Example_Module
					using (IDbConnection con = Database.GetConn("DwProjectTemplate.mdb")) {
						IDbCommand cmdCreateDb = con.CreateCommand();
						cmdCreateDb.CommandText = ""; // DDL to Create the DB tables
						cmdCreateDb.ExecuteNonQuery();
					}
					Dynamicweb.RegisterModules.Module m = new Dynamicweb.RegisterModules.Module()
					{
						Access = true,
						Paragraph = true,
						Name = "Example Module",
						SystemName = "ExampleModule",
						Description = "Best Practices Example Module",
						Script = "/CustomModules/ExampleModule/Default.aspx",
						ControlPanel = "/CustomModules/ExampleModule/ExampleModule_Cpl.aspx",
						SearchSettings = new Dynamicweb.Search.ModuleSettings()
						{
							Database = "DwProjectTemplate",
							ItemTable = "Community_ExampleModule_Item",
							ItemIDQueryParameterName = "ItemId",
							CategoryTable = "Community_ExampleModule_Category",
							CategoryIdField = "Id",
							CategoryNameField = "Name",
							ItemIdField = "Id",
							ItemCategoryIdField = "CategoryId",
							ItemNameField = "Name",
							ItemDateField = "CreateDateTime",
							ItemLastModifiedDateField = "UpdateDateTime",
							ItemSearchFields = "Name",
							ItemTextField = "Name",
							ItemActiveFromDateField = "",
							ItemActiveToDateField = "",
							ItemActiveField = "Active",
							ModuleName = "Example Module",
							SystemName = "ExampleModule" // Important or it won't save
						}
					};
					m.Save();
				}
			}
		}
	}
}

